from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.faker import Faker
import json


def get_data(data, key):
    value = data.get(key)
    if value is None:
        value = 0
    return value

def make_xdata(data, fieldname):
    result = []
    count = data["result"]["count"]
    _data = data["result"]["data"]
    for _ in _data:
        result.append(get_data(_,"REPORT_DATE_NAME"))
    result.reverse()
    return result

def make_yaxisdata(datadict, FromYear,ToYear,Ctype):
    result = []
    length = FromYear - ToYear
    count = 0
    for i in range(ToYear,FromYear + 1):
        yeardata = []
        for code in datadict.keys():
            data = datadict[code]["lirun"]
            _data = data["result"]["data"][length - count]
            yeardata.append(round(get_data(_data,Ctype)/100000000,0))
        pair = (str(i),yeardata)
        result.append(pair)
        count = count + 1
    return result

def makechart_compare(datadict,xdatalist,FromYear=2023, ToYear=2014, Ctype="TOTAL_PROFIT",Title="逐年利润比较图"):
    # 创建 Bar 对象
    bar = Bar()
    # 添加 x 轴数据
    # bar.add_xaxis(Faker.choose())
    bar.add_xaxis(xdatalist)
    # 动态添加 y 轴数据
    yaxis_data = make_yaxisdata(datadict, FromYear,ToYear,Ctype)
    # yaxis_data = [
    #     ("商家A", Faker.values()),
    #     ("商家B", Faker.values()),
    #     ("商家C", Faker.values())
    # ]
    for name, values in yaxis_data:
        bar.add_yaxis(name, values, category_gap="60%")
    # 设置全局选项
    bar.set_global_opts(title_opts=opts.TitleOpts(title=Title))
    # 渲染为 HTML 文件
    bar.render(Title + ".html")

if __name__ == "__main__":
    makechart_compare([])